package com.eco.fanliapp.controller.app;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.base.BaseController;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.entity.SyUserWxContrast;
import com.eco.fanliapp.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 * app微信提现接口
 */
@RestController
@RequestMapping("/app/cash/withdrawal")
public class AppWxWithdrawalController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(AppWxWithdrawalController.class);

    @Autowired
    private IAppWxWithdrawalService appWxWithdrawalService;

    @Autowired
    private ISyUserWxContrastService syUserWxContrastService;

	/**
     * 微信提现（企业付款）
     *
     * @return
     */
    @PostMapping(value = "/toGet")
    public ServerResponse toGet(@RequestBody Map map){
        Calendar now = Calendar.getInstance();
        Integer month = (now.get(Calendar.MONTH) + 1);
        Integer day = now.get(Calendar.DAY_OF_MONTH);

        if(month == 1 && day > 21 && day < 31){
            return ServerResponse.createByErrorMessage("温馨提示：春节假期期间暂停提现，敬请谅解。");
        }
        try {
            AppUser user = getAppUser();
            if(null == user) {
                return ServerResponse.createByErrorCodeMessage(301,"Token不正确");
            }
            return appWxWithdrawalService.toGet(MapUtils.getString(map,"amount"),user.getUserId(),1);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("提现失败！");
        }
    }
    @PostMapping(value = "/toGetTest")
    public ServerResponse toGetTest(String amount,Long userId){
        try {

            return appWxWithdrawalService.toGet(amount,userId,1);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("提现失败");
        }
    }
    /**
     * 微信提现（查询企业付款）
     *
     * @return
     */
    @PostMapping(value = "/gettransferinfo")
    public ServerResponse gettransferinfo(@RequestBody Map map) {
        return appWxWithdrawalService.gettransferinfo();
    }
    /**
     * 微信提现规则
     *
     * @return
     */
    @GetMapping(value = "/rules")
    public ServerResponse rules() {
        AppUser appUser = getAppUser();
        return appWxWithdrawalService.rules(appUser.getUserId());
    }

    /**
     * 微信提现记录
     *
     * @return
     */
    @GetMapping(value = "/selectWithdrawalList")
    public ServerResponse appWithdrawalList(@RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "10") int pageSize, Integer withdrawalType) {
        AppUser u = getAppUser();
        if(null == u) {
            return ServerResponse.createByErrorCodeMessage(301,"Token不正确");
        }
        return appWxWithdrawalService.appWithdrawalList(currentPage,pageSize,u.getUserId(),withdrawalType);
    }

    /**
     * 校验当前用户是否关注公众号
     * @param amount  提现选择的金额
     * @return
     * @throws ParseException
     * @throws IOException
     */
    @GetMapping("/wxFoucs")
    @ResponseBody
    public ServerResponse<String> wxFoucs(String amount) throws ParseException, IOException {
        AppUser u = getAppUser();
        if(null == u) {
            return ServerResponse.createByErrorCodeMessage(301,"Token不正确");
        }
        String unionId = u.getWechatUnionid();
        log.info("该用户unionId:" + unionId);
        //判断用户是否关注过公众号
        QueryWrapper<SyUserWxContrast> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("union_id",unionId);
        queryWrapper.eq("enable",true);
        queryWrapper.eq("deleted",false);
        List<SyUserWxContrast> listWxContrast = syUserWxContrastService.list(queryWrapper);
        SyUserWxContrast contrast = null;
        if (CollectionUtils.isNotEmpty(listWxContrast)){
            contrast = listWxContrast.get(0);
            //已经关注公众号，返回提示
            String openId = contrast.getWxOpendId();
			if(openId !=null && !"".equals(openId)){
				return ServerResponse.createBySuccess("该用户已经关注过公众号","1");
			}
        }
        return ServerResponse.createBySuccess("该用户未关注过公众号","0");

    }

    /**
     * 发送消息通知
     * @param messageType   发送消息的类型（30001：提现到账通知，30002：下单成功提醒，30003：收货成功提醒，30004：好友下单成功提醒，30005：邀请好友成功）
     * @param keyword1Param  消息体1
     * @param keyword2Param  消息体2
     * @param keyword3Param  消息体3
     * @param keyword4Param  消息体4
     * @return
     * @throws ParseException
     * @throws IOException
     */
    @GetMapping("/sendCashMessage")
    @ResponseBody
    public ServerResponse<String> sendCashMessage(String messageType, String keyword1Param, String keyword2Param, String keyword3Param, String keyword4Param) throws ParseException, IOException {

        AppUser u = getAppUser();
        if(null == u) {
            return ServerResponse.createByErrorCodeMessage(301,"Token不正确");
        }
        log.info("该用户unionId:" + u.getWechatUnionid());

        return appWxWithdrawalService.sendCashMessage(u, messageType, keyword1Param, keyword2Param, keyword3Param, keyword4Param);
    }
}
